package com.olive;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 消费者2（发布订阅模式）
 */
public class PubSubConsumer2 {

	// 队列名称
	private static final String QUEUE_NAME2 = "fanout_queue2";
	// 交换机名称
	private static final String EXCHANGE_NAME = "fanout_exchange";

	public static void main(String[] args) throws Exception {
		// 1、获取连接对象
		Connection connection = ConnectionUtils.getConnection();
		// 2、创建通道（频道）
		Channel channel = connection.createChannel();
		// 3、声明交换机,如果没有名称为EXCHANGE_NAME的交换机则创建，有则不创建
		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT, true);
		// 4、声明队列Queue。channel.queueDeclare(队列名称，是否持久化，是否独占本连接,是否自动删除,附加参数)
		channel.queueDeclare(QUEUE_NAME2, true, false, false, null);
		// 5、绑定队列和交换机。channel.queueBind(队列名, 交换机名, 路由key[fanout交换机的routingKey设置为""])
		channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "");
		// 6、监听队列，接收消息
		DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				// 获取交换机信息
				String exchange = envelope.getExchange();
				// 获取消息信息
				String message = new String(body, "utf-8");
				System.out.println("交换机名称:" + exchange + ",消费者获取消息: " + message);
			}
		};
		channel.basicConsume(QUEUE_NAME2, true, defaultConsumer);
		// 注意，消费者这里不建议关闭资源，让程序一直处于读取消息的状态
	}
}